package org.csu.mypetstore.controller;

import org.csu.mypetstore.common.CommonResponse;
import org.csu.mypetstore.domain.*;
import org.csu.mypetstore.service.CartService;
import org.csu.mypetstore.service.CatalogService;
import org.csu.mypetstore.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@RestController
@RequestMapping("/cart")
public class CartController {

    @Autowired
    private CartService cartService;

    @Autowired
    private CatalogService catalogService;
    @Autowired
    private UserService userService;

    //    @GetMapping("/viewCart")
//    public String viewCart(HttpServletRequest request, Model model){
//        HttpSession session = request.getSession();
//        User user = (User) session.getAttribute("user");
//        if(user != null) {
//            String username = user.getUsername();
//            List<CartItem> cart = cartService.selectItemByUsername(username);
//
//
//            if (cart == null) {
//                cart = new ArrayList<CartItem>();
//            }
//
//            //用于传购物车Item每个的库存量  暂未实现 双条件 th:each
//            Iterator cartIterator = cart.iterator();
//            List<Integer> qtyList = new ArrayList<>();
//            while(cartIterator.hasNext()){
//                CartItem cartItem = (CartItem) cartIterator.next();
//                Item item = cartItem.getItem();
//                int qty=catalogService.getInventoryQuantity(item.getItemId());
//                qtyList.add(qty);
//            }
//            Iterator qtyListIterator = qtyList.iterator();
//            model.addAttribute("qtyListIterator",qtyListIterator);
//
//            session.setAttribute("cart",cart);
//            model.addAttribute("cart", cart);
//            model.addAttribute("user",user);
//            return "/cart/Cart";
//        }
//        else{
//            String msg="请先登录后再查看购物车";
//            model.addAttribute("msg",msg);
//            return "/account/Signin";
//        }
//    }
    @GetMapping("/viewCart")
    public CommonResponse<Object> viewCart(HttpSession session){
        User user = (User) session.getAttribute("user");
        System.out.println(user);
        if(user != null) {
            String username = user.getUsername();
            List<CartItem> cart = cartService.selectItemByUsername(username);
            for(CartItem c:cart){
                System.out.println(c.getItem().getItemId());
            }
            System.out.println(cart);
            if (cart == null) {
                cart = new ArrayList<CartItem>();
            }

            //用于传购物车Item每个的库存量  暂未实现 双条件 th:each
            Iterator cartIterator = cart.iterator();
            List<Integer> qtyList = new ArrayList<>();
            while(cartIterator.hasNext()){
                CartItem cartItem = (CartItem) cartIterator.next();
                Item item = cartItem.getItem();
                int qty=catalogService.getInventoryQuantity(item.getItemId());
                qtyList.add(qty);
            }
            Iterator qtyListIterator = qtyList.iterator();
            session.setAttribute("cart",cart);
            return CommonResponse.createForSuccess(cart,user,qtyListIterator);
        }
        else{
            String msg="请先登录后再查看购物车";
            return CommonResponse.createForError(msg);
        }
    }

//    @GetMapping("/addItemToCart")
//    public String addItemToCart(String workingItemId,HttpServletRequest request,Model model){
//        HttpSession session = request.getSession();
//        User user = (User) session.getAttribute("user");
//        if(user!=null){model.addAttribute("user",user);}
//
//        if(user == null){
//            String msg = "请先登录再加入购物车！";
//            model.addAttribute("msg",msg);
//            return "/account/Signin";
//        }
//        else {
//            String username = user.getUsername();
//            CartItem cartItem = cartService.getCartItemByUsernameAndItemId(username, workingItemId);
//
//            if (cartItem != null) {
//                if(!cartItem.isPay()) {
//                    cartService.incrementItemByUsernameAndItemId(username, workingItemId);
//                }
//                else {
//                    cartService.updateItemByItemIdAndPay(username, workingItemId, false);
//                    cartService.updateItemByItemIdAndQuantity(username, workingItemId, 1);
//                }
//            } else {
//                boolean isInStock = catalogService.isItemInStock(workingItemId);
//                Item item = catalogService.getItem(workingItemId);
//                cartService.addItemByUsernameAndItemId(username, item, isInStock);
//            }
//            List<CartItem> cart = (List<CartItem>) session.getAttribute("cart");
//            if (cart == null) {
//                cart = new ArrayList<CartItem>();
//            }
//            cart = cartService.selectItemByUsername(username);
//            Iterator cartIterator = cart.iterator();
//            List<Integer> qtyList = new ArrayList<>();
//            while(cartIterator.hasNext()){
//                CartItem cartItem2 = (CartItem) cartIterator.next();
//                Item item = cartItem2.getItem();
//                int qty=catalogService.getInventoryQuantity(item.getItemId());
//                qtyList.add(qty);
//            }
//            Iterator qtyListIterator = qtyList.iterator();
//            model.addAttribute("qtyListIterator",qtyListIterator);
//            session.setAttribute("cart", cart);
//            model.addAttribute("cart", cart);
//            return "/cart/Cart";
//        }
//    }
    @PostMapping("/addItemToCart")
    public CommonResponse<Object> addItemToCart(@RequestParam("workingItemId") String workingItemId,
                                                HttpSession session){
        System.out.println("aaa");
        System.out.println(session.getId());
        User user = (User) session.getAttribute("user");
        System.out.println(user.getUsername()+"调用");
        //User user = userService.getUser("1234");
        String username = user.getUsername();
        System.out.println(workingItemId);
        CartItem cartItem = cartService.getCartItemByUsernameAndItemId(username, workingItemId);
        if (cartItem != null) {
            if(!cartItem.isPay()) {cartService.incrementItemByUsernameAndItemId(username, workingItemId);}
            else {cartService.updateItemByItemIdAndPay(username, workingItemId, false);cartService.updateItemByItemIdAndQuantity(username, workingItemId, 1);}
        } else {
            boolean isInStock = catalogService.isItemInStock(workingItemId);
            Item item = catalogService.getItem(workingItemId);
            cartService.addItemByUsernameAndItemId(username, item, isInStock);
        }
        List<CartItem> cart = (List<CartItem>) session.getAttribute("cart");
        if (cart == null) {cart = new ArrayList<CartItem>();}
        cart = cartService.selectItemByUsername(username);
        Iterator cartIterator = cart.iterator();
        List<Integer> qtyList = new ArrayList<>();
        while(cartIterator.hasNext()){
            CartItem cartItem2 = (CartItem) cartIterator.next();
            Item item = cartItem2.getItem();
            int qty=catalogService.getInventoryQuantity(item.getItemId());
            qtyList.add(qty);
        }
        Iterator qtyListIterator = qtyList.iterator();
        session.setAttribute("cart",cart);
        return CommonResponse.createForSuccess(user,qtyListIterator,cart);
    }

//    @GetMapping("/removeItemFromCart")
//    public String removeItemFromCart(String itemId,HttpServletRequest request,Model model){
//        HttpSession session = request.getSession();
//        User user = (User) session.getAttribute("user");
//        if(user!=null){model.addAttribute("user",user);}
//        if(user == null){
//            String msg = "Please sign in first.！";
//            model.addAttribute("msg",msg);
//            return "/account/Signin";
//        }
//        else {
//            String username = user.getUsername();
//            CartItem cartItem = cartService.getCartItemByUsernameAndItemId(username, itemId);
//            if (cartItem == null) {
//                String msg="Attempted to remove all null CartItem from Cart.";
//                model.addAttribute("msg",msg);
//                return "common/Error";
//            } else {
//                cartService.removeCartItemByUsernameAndItemId(username, itemId);
//                List<CartItem> cart = cartService.selectItemByUsername(username);
//                Iterator cartIterator = cart.iterator();
//                List<Integer> qtyList = new ArrayList<>();
//                while(cartIterator.hasNext()){
//                    CartItem cartItem2 = (CartItem) cartIterator.next();
//                    Item item = cartItem2.getItem();
//                    int qty=catalogService.getInventoryQuantity(item.getItemId());
//                    qtyList.add(qty);
//                }
//                Iterator qtyListIterator = qtyList.iterator();
//                model.addAttribute("qtyListIterator",qtyListIterator);
//                session.setAttribute("cart", cart);
//                model.addAttribute("cart",cart);
//                return "/cart/Cart";
//            }
//        }
//    }
    @GetMapping("/removeItemFromCart")
    public CommonResponse<Object> removeItemFromCart(@RequestParam("itemId") String itemId,
                                                     HttpSession session){
        User user = (User) session.getAttribute("user");
        if(user == null){
            String msg = "Please sign in first.！";
            return CommonResponse.createForError(msg);
        }
        else {
            String username = user.getUsername();
            CartItem cartItem = cartService.getCartItemByUsernameAndItemId(username, itemId);
            if (cartItem == null) {
                String msg="Attempted to remove all null CartItem from Cart.";
                return CommonResponse.createForError(msg);
            } else {
                cartService.removeCartItemByUsernameAndItemId(username, itemId);
                List<CartItem> cart = cartService.selectItemByUsername(username);
                Iterator cartIterator = cart.iterator();
                List<Integer> qtyList = new ArrayList<>();
                while(cartIterator.hasNext()){
                    CartItem cartItem2 = (CartItem) cartIterator.next();
                    Item item = cartItem2.getItem();
                    int qty=catalogService.getInventoryQuantity(item.getItemId());
                    qtyList.add(qty);
                }
                Iterator qtyListIterator = qtyList.iterator();
                return CommonResponse.createForSuccess(user,qtyListIterator,cart);
            }
        }
    }

    @PostMapping("/updateCartItem")
    public void updateCartItem(@RequestParam("itemId") String itemId,
                               @RequestParam("quantity") String quantityStr,
                               HttpSession session) throws IOException {

        User user;


        user = (User) session.getAttribute("user");
        String username = user.getUsername();
        int quantity = 0;


        System.out.println();



        if(quantityStr == "" || quantityStr.equals(null)){
            cartService.removeCartItemByUsernameAndItemId(username, itemId);

        }
        else {
            quantity = Integer.parseInt(quantityStr);
            System.out.println(itemId+"数量"+quantity);
            if(quantity == 0){
                cartService.removeCartItemByUsernameAndItemId(username, itemId);

            }
            else {
                cartService.updateItemByItemIdAndQuantity(username, itemId, quantity);
                CartItem item = cartService.getCartItemByUsernameAndItemId(username, itemId);
                String html = "<fmt:formatNumber type='number' pattern='$#,##0.00'>$" + item.getTotal() + "</fmt:formatNumber>";
                //System.out.println("html"+html);

            }
        }
        List<CartItem> cart = cartService.selectItemByUsername(username);
        session.setAttribute("cart", cart);

    }

}
